#!/bin/sh

TARGET=192.168.20.200
NUMP=1
IFACE=br0
MAC=10:6f:3f:a8:03:41
WOL=/usr/sbin/ether-wake
INTERVAL=20
LOGFILE="/var/log/ether-wake.log"
U=sihan
P=Windows112
DIR=Sihan-Nas

# ping
getping ()
{
if ! ping -qc $NUMP $1 >/dev/null; then
    echo "F"
else
   echo "T"
fi
}

# wol 
wakeone ()
{
    echo "WAKE $TARGET at" `date`>> $LOGFILE
    $WOL -i $IFACE $MAC
}

wake ()
{
    while sleep $INTERVAL;do
	wakeone
    done
}

creatdir () 
{
    while [ ! -d /mnt/$DIR ];do
        mkdir /mnt/$DIR
        sleep $INTERVAL
    done
}


mountnasdir ()
{
	if ! mount -t cifs -o username=$U,password=$P //$TARGET/$DIR /mnt/$DIR >/dev/null; then
		echo "F"
	else
		echo "T"
	fi
}


nasmount ()
{
    while [ $(getping "$TARGET") == 'F' ];do
        wakeone
        sleep $INTERVAL
    done

    creatdir

    while [ $(mountnasdir) == 'F' ];do
         mountnasdir
        sleep $INTERVAL
    done

    echo "finsh"
}


if [ "$1" == "wake" ]; then
    wake
elif [ "$1" == "mount" ]; then
    nasmount
else
    echo "{$1} parameter error, plese input 'wake' or 'mount'"
    exit 1
fi